package com.steward.server.user.impl;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.steward.dao.customer.CustomerMapper;
import com.steward.dao.mob.MobRegMapper;
import com.steward.model.customer.Customer;
import com.steward.model.mob.MobReg;
import com.steward.server.user.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

	private static Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Resource
    private MobRegMapper mobRegMapper;
    
    @Resource
    private CustomerMapper customerMapper;


	@Override
	public JSONObject loginToRegister(String account, String verifiCode,HttpSession httpSession) {
		// 通过手机号和验证码验证是否合法
		MobReg reg = mobRegMapper.selectMobRegByPhoneAndCode(account, verifiCode);

		//通过验证后，根据手机查询客户表是否存在客户，不存在新建
		if(reg!=null){
			Customer customer ;
			List<Customer> list = customerMapper.selectCustomersByPhone(account);
			if(list!=null&&list.size()>0){
				 customer = list.get(0);
			}else{
				String uuid = UUID.randomUUID().toString();
				String uuid2 = UUID.randomUUID().toString();
			    customer = new Customer();
				customer.setTelphone(account);
				customer.setAddDate(new Date());
				customer.setShopId(uuid2);
				customer.setId(uuid);
				customerMapper.insert(customer);
			}
			//唯一标识
			httpSession.setAttribute(customer.getId(), customer);

			//更新到手机注册表
			reg.setLatestAccessToken(httpSession.getId());
			//reg.setTokenCreatedDate(Calendar.getInstance().getTime().getTime());
			reg.setCustomerid(customer.getId());
			JSONObject obj = new JSONObject();
			try {
				obj.put("code", 200);
				obj.put("UserID", customer.getId());
				obj.put("CustomerID", reg.getId());
				obj.put("accessToken", httpSession.getId());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return obj;

		}else{
			JSONObject obj = new JSONObject();
			try {
				obj.put("code", 400);
				obj.put("message", "手机验证失败");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return obj;
		}


	}



}
